package com.yygo.webapp.controller.loanrequest;

import com.yygo.model.Feedback;
import com.yygo.model.LoanRequest;
import com.yygo.model.User;
import com.yygo.model.enums.FeedbackType;
import com.yygo.model.vo.FeedbackVO;
import com.yygo.service.FeedbackManager;
import com.yygo.service.UserManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ExtendedModelMap;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import java.security.Principal;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by tiansha on 2015/10/4.
 */

@Controller
@RequestMapping("/materialRequests*")
public class MaterialRequestsController {

    @Autowired
    private UserManager userManager;

    @Autowired
    private FeedbackManager feedbackManager;

    @RequestMapping(method = RequestMethod.GET)
    @ModelAttribute
    public ModelAndView handleRequest(Principal principal) {
        User currentUser = userManager.getUserByUsername(principal.getName());
        List<Feedback> feedbackList = feedbackManager.getFeedbacks(currentUser);
        List<LoanRequest> materialRequests = new ArrayList<>();
        for (Feedback feedback : feedbackList) {
            if (feedback.getFeedbackType().equals(FeedbackType.MaterialType)) {
                materialRequests.add(feedback.getLoanRequest());
            }
        }

        Model model = new ExtendedModelMap();
        model.addAttribute("loanRequestList", materialRequests);
        return new ModelAndView("myloanrequests", model.asMap());
    }
}
